package dbexp.model;

import static dbexp.model.db.DbOT.*;

import java.util.ArrayList;
import java.util.List;

public class Index extends DbObject {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private List<Column> kolumny = new ArrayList<Column>();
	public static final String LABEL = "indeksy";
	public static final String DEF_ICON = "index-icon";

	public Index() {
		super(LABEL, INDEXES);
		setIcons(DEF_ICON);
	}

	public Index(String indexName) {
		super(indexName, INDEX);
		setIcons(DEF_ICON);
		set("leaf", true);
	}

	public Index(String indexName, String schema) {
		this(indexName);
		setSchema(schema);
	}

	public String onSchema() {
		return get("onSchema");
	}

	public void setOnSchema(String onSchema) {
		set("onSchema", onSchema);
	}

	public String onTable() {
		return get("onTable");
	}

	public void setOnTable(String onTable) {
		set("onTable", onTable);
	}

	public String getTablespace() {
		return get("TABLESPACE");
	}

	public void setTablespace(String tablespace) {
		set("TABLESPACE", tablespace);
	}

	public boolean isUnique() {
		return is("UNIQUE");
	}

	public void setUnique(boolean unique) {
		set("UNIQUE", unique);
	}

	public boolean isBitmap() {
		return is("BITMAP");
	}

	public void setBitmap(boolean bitmap) {
		set("BITMAP", bitmap);
	}

	public boolean isUnsorted() {
		return is("UNSORTED");
	}

	public void setUnsorted(boolean unsorted) {
		set("UNSORTED", unsorted);
	}

	public boolean isReverse() {
		return is("REVERSE");
	}

	public void setReverse(boolean reverse) {
		set("REVERSE", reverse);
	}

	public void setColumns(List<Column> cols) {
		this.kolumny = cols;
		set("cols", cols);
	}

	public List<Column> getColumns() {
		return this.kolumny;
	}

	public void addColumn(Column col) {
		this.kolumny.add(col);
	}

	public Column getCols(int i) {
		return this.kolumny.get(i);
	}

	private String getQuery(String oper) {
		if (requiredFieldIsNotNull()) {
			String query = ((isBitmap() ? "BITMAP " : (isUnique()) ? "UNIQUE "
					: ""))
					+ "INDEX " + getObjectNameForQuery() + " ON \n";
			query += "\"" + onSchema() + "\".\"" + onTable() + "\" ";
			if (kolumny.size() > 0) {
				query += "(";
			}
			for (int i = 0; i < kolumny.size(); i++) {
				query += "\"" + kolumny.get(i).getName() + "\"";
				if (i < (kolumny.size() - 1)) {
					query += ",";
				}
			}
			if (kolumny.size() > 0) {
				query += ")";
			}
			if (isBitmap()) {
				return oper + query;
			}
			return oper
					+ query
					+ ((isUnsorted()) ? " UNSORTED"
							: (isReverse()) ? " REVERSE" : "");
		} else {
			return oneFromDual();
		}
	}

	public String getQuery(int operation) {
		if (operation == CREATE) {
			return getQuery("CREATE ");
		} else if (operation == ALTER) {
			return getQuery("ALTER ");
		} else if (operation == DELETE) {
			return "DROP INDEX " + getObjectNameForQuery() + "";
		}
		return oneFromDual();
	}
}
